{% extends "base.html" %}

{% block title %}对话记录 - 智能竞赛信息平台{% endblock %}

{% block content %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/chat_history.css') }}">

<div class="content-area">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="page-title">对话记录</h1>
        <p class="page-subtitle">查看您的AI助手对话历史</p>
    </div>

    <div class="chat-history-container">
        <!-- 流式聊天区域 -->
        <!-- <div class="stream-chat-test">
            <h3>AI竞赛助手</h3>
            <p>和AI实时交流，获取个人专属的竞赛推荐方案</p>
            <div class="stream-chat-container">
                <div class="chat-messages" id="streamChatMessages"></div>
                <div class="chat-input-container">
                    <textarea 
                        id="streamChatInput" 
                        placeholder="请输入您的问题..."
                        rows="3"
                    ></textarea>
                    <button id="streamChatSend">发送</button>
                </div>
            </div>
        </div> -->

        <!-- 对话列表 -->
        <div class="conversations-list" id="conversationsList">
            <!-- 对话项目将通过JavaScript动态加载 -->
        </div>

        <!-- 加载状态 -->
        <div id="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p class="loading-text">加载对话记录中...</p>
        </div>

        <!-- 无对话记录提示 -->
        <div id="no-conversations" class="no-conversations" style="display: none;">
            <iconify-icon icon="material-symbols:chat-bubble-outline" width="48" style="color: #9CA3AF;"></iconify-icon>
            <h3>暂无对话记录</h3>
            <p>开始与AI助手对话，记录将在这里显示</p>
            <button class="start-chat-btn" onclick="startNewChat()">
                <iconify-icon icon="material-symbols:chat" width="16"></iconify-icon>
                开始新对话
            </button>
        </div>
    </div>
</div>



<script>
// 竞赛处理相关函数（复用ai-chat.js中的逻辑）
// 竞赛缓存，避免重复查询
const competitionCache = new Map();

// 提取竞赛名称
function extractCompetitionName(text) {
    // 更严格的匹配规则：必须包含"竞赛名称："前缀
    const pattern = /竞赛名称[:：]\s*(.+?)\s*(?:比赛|竞赛)?\s*$/i;
    
    const m = text.match(pattern);
    if (m && m[1]) {
        let name = m[1].trim()
            .replace(/["""']+/g, '')
            .replace(/[。；;,.、]+$/g, '');
            
        // 去除括号内的内容（包括中文和英文括号）
        name = name.replace(/[（(].*?[）)]/g, '');
        
        // 过滤掉明显不是竞赛名称的文本
        if (name.length >= 2 && name.length <= 30 && 
            !name.includes('适合原因') && 
            !name.includes('竞赛时间') && 
            !name.includes('你是山东大学') &&
            !name.includes('培养方案') &&
            !name.includes('专业核心课程')) {
            return name;
        }
    }
    return null;
}

// 搜索竞赛数据
async function searchCompetition(name) {
    if (!name) return null;
    
    // 构建搜索策略
    const strategies = [
        name, // 原始名称
        name.replace(/[（(].*?[）)]/g, '').trim(), // 去除括号内容
        name.replace(/\s+/g, ''), // 去除所有空格
        ...(name.match(/[（(]([A-Z]+)[）)]/) ? [name.match(/[（(]([A-Z]+)[）)]/)[1]] : []), // 括号内英文缩写
        name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '') // 去除标点
    ].filter(s => s && s.length > 1);
    
    console.log('[竞赛搜索] 搜索策略:', strategies);
    
    for (const term of strategies) {
        try {
            const url = `/api/competitions/search?q=${encodeURIComponent(term)}`;
            console.log('[竞赛搜索] 尝试搜索:', term, 'URL:', url);
            
            const resp = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });
            
            if (!resp.ok) {
                console.warn('[竞赛搜索] 请求失败:', resp.status);
                continue;
            }
            
            const data = await resp.json();
            console.log('[竞赛搜索] 响应数据:', data);
            
            if (Array.isArray(data) && data.length > 0) {
                return data.find(c => (c.name || '').trim() === term) || data[0];
            }
        } catch (e) {
            console.error('[竞赛搜索] 搜索错误:', e);
        }
    }
    return null;
}

// 添加查看详情按钮
function addDetailButton(element, competition) {
    if (!element || !competition) return;
    
    // 检查是否已经添加过按钮
    if (element.querySelector('.comp-ref-btn')) return;
    
    const button = document.createElement('button');
    button.className = 'comp-ref-btn';
    button.textContent = '查看详情';
    button.style.cssText = `
        margin-left: 8px;
        padding: 4px 8px;
        background: #2A5CAA;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 12px;
        cursor: pointer;
    `;
    
    // 将竞赛信息保存到按钮的data属性中，用于本地恢复
    button.dataset.competition = JSON.stringify(competition);
    
    button.addEventListener('click', (e) => {
        e.stopPropagation();
        if (typeof window.showCompetitionDetail === 'function') {
            window.showCompetitionDetail(competition);
        }
    });
    
    element.appendChild(button);
    console.log('[按钮添加] 已为竞赛添加按钮:', competition.name);
}

// 处理单个p标签的竞赛检索
async function processParagraphForCompetitions(pElement) {
    if (!pElement || pElement.hasAttribute('data-competition-processed')) return;
    
    try {
        pElement.setAttribute('data-competition-processed', 'processing');
        const text = (pElement.textContent || '').trim();
        
        const name = extractCompetitionName(text);
        if (!name) {
            pElement.removeAttribute('data-competition-processed');
            return;
        }
        
        console.log('[竞赛处理] 提取到竞赛名称:', name);
        
        // 检查缓存
        if (competitionCache.has(name)) {
            const comp = competitionCache.get(name);
            addDetailButton(pElement, comp);
            pElement.setAttribute('data-competition-processed', 'done');
            return;
        }
        
        const comp = await searchCompetition(name);
        if (!comp) {
            pElement.removeAttribute('data-competition-processed');
            return;
        }
        
        // 缓存结果
        competitionCache.set(name, comp);
        addDetailButton(pElement, comp);
        pElement.setAttribute('data-competition-processed', 'done');
        
    } catch (e) {
        console.error('[竞赛处理] 处理错误:', e);
        pElement.removeAttribute('data-competition-processed');
    }
}

// 一次性处理容器中所有p标签的竞赛检索
async function processAllParagraphsForCompetitions(container) {
    if (!container) return;
    
    console.log('[竞赛处理] 开始处理历史对话中的竞赛名称');
    
    // 获取所有p标签
    const pElements = container.querySelectorAll('p');
    if (pElements.length === 0) {
        console.log('[竞赛处理] 未找到p标签');
        return;
    }
    
    console.log(`[竞赛处理] 找到 ${pElements.length} 个p标签，开始处理`);
    
    // 批量处理所有p标签
    const promises = Array.from(pElements).map(p => processParagraphForCompetitions(p));
    await Promise.all(promises);
    
    console.log('[竞赛处理] 所有p标签处理完成');
}

// 清理竞赛缓存
function clearCompetitionCache() {
    competitionCache.clear();
    console.log('[竞赛处理] 已清理竞赛缓存');
}

// 重新绑定"查看详情"按钮事件的函数
function rebindDetailButtons(container) {
    try {
        const detailButtons = container.querySelectorAll('.comp-ref-btn');
        detailButtons.forEach(button => {
            // 获取竞赛信息
            const competitionData = JSON.parse(button.dataset.competition || '{}');
            
            // 移除旧的事件监听器并重新绑定
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                if (typeof window.showCompetitionDetail === 'function' && competitionData && competitionData.name) {
                    window.showCompetitionDetail(competitionData);
                }
            });
        });
        
        console.log('[按钮重绑] 已重新绑定', detailButtons.length, '个按钮');
    } catch (error) {
        console.error('[按钮重绑] 重新绑定按钮事件时出错:', error);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    loadChatHistory();
    // 使用ai-chat.js中的AI聊天功能
    if (typeof window.initAIChat === 'function') {
        window.initAIChat();
    }
    
    // 确保页面容器有正确的样式类
    const pageContainer = document.querySelector('.page-container');
    if (pageContainer) {
        // 检查聊天窗口是否已经打开
        const chatWindow = document.getElementById('chatWindow');
        if (chatWindow && chatWindow.classList.contains('open')) {
            pageContainer.classList.add('chat-open');
        }
        
        // 监听聊天窗口状态变化
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                    const chatWindowElement = document.getElementById('chatWindow');
                    if (chatWindowElement) {
                        if (chatWindowElement.classList.contains('open')) {
                            pageContainer.classList.add('chat-open');
                        } else {
                            pageContainer.classList.remove('chat-open');
                        }
                    }
                }
            });
        });
        
        // 开始观察聊天窗口的class变化
        if (chatWindow) {
            observer.observe(chatWindow, { attributes: true });
        }
        
        // 延迟检查状态，确保AI聊天初始化完成
        setTimeout(() => {
            const chatWindow = document.getElementById('chatWindow');
            if (chatWindow && chatWindow.classList.contains('open')) {
                pageContainer.classList.add('chat-open');
                // 如果聊天窗口是打开的，检查是否应该设置历史记录标志
                if (window.currentConversationId) {
                    window.isFromHistoryPage = true;
                    console.log('[历史记录页面] 设置历史记录页面标志');
                }
                
                // 重新绑定聊天窗口中的"查看详情"按钮事件
                const chatMessages = document.getElementById('chatMessages');
                if (chatMessages) {
                    rebindDetailButtons(chatMessages);
                }
            }
        }, 200); // 增加延迟，确保状态恢复完成
    }
});

function loadChatHistory() {
    const container = document.getElementById('conversationsList');
    const loading = document.getElementById('loading');
    const noConversations = document.getElementById('no-conversations');
    
    if (!container) return;
    
    // 显示加载状态
    if (loading) loading.style.display = 'block';
    if (noConversations) noConversations.style.display = 'none';
    container.innerHTML = '';
    
    fetch('/api/chat/history')
        .then(response => response.json())
        .then(data => {
            if (loading) loading.style.display = 'none';
            
            if (data.success && data.conversations && data.conversations.length > 0) {
                renderConversations(data.conversations);
            } else {
                if (noConversations) noConversations.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('加载聊天历史错误:', error);
            if (loading) loading.style.display = 'none';
            if (noConversations) noConversations.style.display = 'block';
        });
}

function renderConversations(conversations) {
    const container = document.getElementById('conversationsList');
    if (!container) return;
    
    container.innerHTML = '';
    
    conversations.forEach(conversation => {
        const item = createConversationItem(conversation);
        container.appendChild(item);
    });
}

function createConversationItem(conversation) {
    const item = document.createElement('div');
    item.className = 'conversation-item';
    item.dataset.id = conversation.id;
    
    const date = window.formatDate ? window.formatDate(conversation.created_at) : '';
    const messageCount = conversation.messages ? conversation.messages.length : 0;
    const preview = getConversationPreview(conversation.messages);
    
    item.innerHTML = `
        <div class="conversation-header">
            <h3 class="conversation-title">${conversation.title}</h3>
            <span class="conversation-date">${date}</span>
        </div>
        <div class="conversation-preview">${preview}</div>
        <div class="conversation-meta">
            <div class="message-count">
                <iconify-icon icon="material-symbols:chat" width="14"></iconify-icon>
                ${messageCount} 条消息
            </div>
            <button class="delete-btn" onclick="deleteConversation('${conversation.id}', event)">
                <iconify-icon icon="material-symbols:delete" width="14"></iconify-icon>
                删除
            </button>
        </div>
    `;
    
    // 添加点击事件
    item.addEventListener('click', function(e) {
        if (!e.target.closest('.delete-btn')) {
            openConversation(conversation);
        }
    });
    
    return item;
}

function getConversationPreview(messages) {
    if (!messages || messages.length === 0) {
        return '暂无消息';
    }
    
    // 获取第一条用户消息作为预览
    for (let message of messages) {
        if (message.type === 'user') {
            return message.content.length > 50 ? 
                message.content.substring(0, 50) + '...' : 
                message.content;
        }
    }
    
    return '暂无消息';
}

// 使用全局的formatDate函数，确保与主页竞赛卡片显示一致
// 本地的formatDate函数已删除，统一使用window.formatDate

function openConversation(conversation) {
    // 清理之前的竞赛缓存，开始新对话
    clearCompetitionCache();
    
    // 设置对话ID
    window.currentConversationId = conversation.id;
    
    // 标记这是从历史记录打开的对话
    window.isFromHistoryPage = true;
    
    // 检查聊天窗口是否已经打开
    const chatWindow = document.getElementById('chatWindow');
    const isAlreadyOpen = chatWindow && chatWindow.classList.contains('open');
    
    // 如果聊天窗口未打开，则点击气泡打开
    if (!isAlreadyOpen) {
        const chatBubble = document.getElementById('chatBubble');
        if (chatBubble) {
            chatBubble.click();
        }
    }
    
    // 延迟执行，确保AI对话窗口已打开或已准备好
    setTimeout(() => {
        const chatWindow = document.getElementById('chatWindow');
        const chatMessages = document.getElementById('chatMessages');
        const chatTitle = document.getElementById('chatTitle');
        const pageContainer = document.querySelector('.page-container');
        
        if (!chatWindow || !chatMessages) {
            console.error('聊天窗口元素未找到');
            return;
        }
        
        // 确保聊天窗口是打开状态
        if (!chatWindow.classList.contains('open')) {
            chatWindow.classList.add('open');
            if (pageContainer) {
                pageContainer.classList.add('chat-open');
            }
        }
        
        // 更新聊天窗口标题
        if (chatTitle) {
            chatTitle.textContent = conversation.title || 'AI竞赛助手';
        }
        
        // 清空当前消息
        chatMessages.innerHTML = '';
        
        // 从服务器获取最新的对话记录
        fetch(`/api/chat/conversation/${conversation.id}`)
        .then(r => r.json())
        .then(data => {
            if (data && data.success && data.conversation && Array.isArray(data.conversation.messages)) {
                // 按时间升序渲染，确保先用户后AI
                const ordered = [...data.conversation.messages].sort((a, b) => {
                    const ta = new Date(a.timestamp || 0).getTime();
                    const tb = new Date(b.timestamp || 0).getTime();
                    return ta - tb;
                });
                
                // 渲染消息
                ordered.forEach(message => {
                    const messageDiv = document.createElement('div');
                    messageDiv.className = `message ${message.type}-message`;
                    
                    // 如果是AI消息且包含Markdown内容，则渲染Markdown
                    if (message.type === 'ai' && message.content && (message.content.includes('```') || message.content.includes('**') || message.content.includes('*') || message.content.includes('#') || message.content.includes('- ') || message.content.includes('1. ') || message.content.includes('[') || message.content.includes('`'))) {
                        const processedText = message.content.replace(/\n/g, '\n\n');
                        messageDiv.innerHTML = marked.parse(processedText);
                    } else {
                        messageDiv.textContent = message.content;
                    }
                    
                    chatMessages.appendChild(messageDiv);
                });
                
                // 滚动到底部
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                // 等待Markdown渲染完成后再处理竞赛名称
                setTimeout(() => {
                    processAllParagraphsForCompetitions(chatMessages);
                    // 重新绑定"查看详情"按钮事件
                    rebindDetailButtons(chatMessages);
                }, 200);
                
                // 保存AI对话窗口状态，确保展开状态持久化
                if (typeof window.saveAIChatState === 'function') {
                    setTimeout(() => {
                        window.saveAIChatState();
                        console.log('[历史记录] 已保存AI对话窗口展开状态');
                    }, 100);
                }
            }
        })
        .catch(error => {
            console.error('获取对话记录失败:', error);
            // 如果获取失败，使用本地数据作为备用
            if (conversation.messages && conversation.messages.length > 0) {
                const ordered = [...conversation.messages].sort((a, b) => {
                    const ta = new Date(a.timestamp || 0).getTime();
                    const tb = new Date(b.timestamp || 0).getTime();
                    return ta - tb;
                });
                
                ordered.forEach(message => {
                    const messageDiv = document.createElement('div');
                    messageDiv.className = `message ${message.type}-message`;
                    messageDiv.textContent = message.content;
                    chatMessages.appendChild(messageDiv);
                });
                
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                // 重新绑定"查看详情"按钮事件
                rebindDetailButtons(chatMessages);
            }
        });
        
        // 聚焦到输入框
        const chatInput = document.getElementById('chatInput');
        if (chatInput) {
            chatInput.focus();
        }
        
    }, isAlreadyOpen ? 50 : 100); // 如果已经打开，减少延迟时间
    
    console.log('正在打开对话:', conversation.id, '标题:', conversation.title, '聊天窗口已打开:', isAlreadyOpen);
}

function deleteConversation(conversationId, event) {
    event.stopPropagation();
    
    if (!confirm('确定要删除这个对话记录吗？')) {
        return;
    }
    
    fetch(`/api/chat/conversation/${conversationId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 从DOM中移除对话项
            const item = document.querySelector(`[data-id="${conversationId}"]`);
            if (item) {
                item.remove();
            }
            
            // 检查是否还有其他对话
            const remainingItems = document.querySelectorAll('.conversation-item');
            if (remainingItems.length === 0) {
                document.getElementById('no-conversations').style.display = 'block';
            }
        } else {
            alert('删除失败，请重试');
        }
    })
    .catch(error => {
        console.error('删除对话错误:', error);
        alert('删除失败，请重试');
    });
}

function startNewChat() {
    // 清除当前对话ID，开始新对话
    window.currentConversationId = null;
    let currentConversationId = null;
    
    // 触发AI聊天窗口
    const chatBubble = document.getElementById('chatBubble');
    if (chatBubble) {
        chatBubble.click();
    }
    
    // 确保页面布局也相应调整
    const pageContainer = document.querySelector('.page-container');
    if (pageContainer) {
        pageContainer.classList.add('chat-open');
        
        // 恢复左侧功能区的宽度调整（如果有保存的话）
        const savedWidth = localStorage.getItem('leftPanelWidth');
        if (savedWidth) {
            const widthValue = parseInt(savedWidth);
            pageContainer.style.marginRight = savedWidth;
            pageContainer.style.maxWidth = `calc(100% - ${widthValue}px)`;
            console.log('[历史记录] 开始新对话时已恢复左侧功能区宽度调整:', savedWidth);
        }
    }
    
    // 保存AI对话窗口状态，确保展开状态持久化
    if (typeof window.saveAIChatState === 'function') {
        // 延迟保存，确保所有状态都已设置完成
        setTimeout(() => {
            window.saveAIChatState();
            console.log('[历史记录] 开始新对话时已保存AI对话窗口展开状态');
        }, 100);
    }
}

</script>
{% endblock %}
